package cn.dmrliu.edu.realtime.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtil {

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dtfFull = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 将日期字符串转为时间戳
    public static Long toTs(String date, boolean isFull) {
        LocalDateTime localDateTime = null;
        if (!isFull) {
            date = date + " 00:00:00";
        }
        localDateTime = LocalDateTime.parse(date, dtfFull);
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    // 将日期字符串转为时间戳,日期不带时间
    public static Long toTs(String date) {
        return toTs(date, false);
    }

    // 将时间戳转为日期
    public static String toDate(Long ts) {
        Date date = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dtf.format(localDateTime);
    }

    // 将时间戳转为日期时间
    public static String toYmdHms(Long ts) {
        Date date = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dtfFull.format(localDateTime);
    }


}
